package controller

import (
	"encoding/hex"
	"md52phone/global"
	"md52phone/pkg/app"
	"strings"

	"github.com/gin-gonic/gin"
)

type Md5Controller struct{}

func NewMd5Controller() *Md5Controller {
	return &Md5Controller{}
}

type queryPhoneObj struct {
	Phone string `json:"phone"`
	Md5   string `json:"md5"`
}

func (s *Md5Controller) Query(c *gin.Context) {
	md5Str := c.DefaultQuery("md5", "")
	if md5Str == "" {
		app.Error(c, app.ParamsError.Code, app.ParamsError.Msg)
		return
	}
	if strings.Contains(md5Str, ",") {
		var result []*queryPhoneObj
		md5Strs := strings.Split(md5Str, ",")
		var tts [][]byte
		for _, item := range md5Strs {
			tt, err := hex.DecodeString(item)
			if err != nil {
				result = append(result, &queryPhoneObj{Phone: "", Md5: item})
				continue
			}
			tts = append(tts, tt)
		}
		values, _ := global.Service.BatchQuery(tts)
		for k, v := range values {
			result = append(result, &queryPhoneObj{Phone: v, Md5: k})
		}
		app.Success(c, result)
	} else {
		var result []*queryPhoneObj
		tt, err := hex.DecodeString(md5Str)
		if err != nil {
			result = append(result, &queryPhoneObj{Phone: "", Md5: md5Str})
			app.Success(c, result)
			return
		}
		value, _ := global.Service.Query(tt)
		result = append(result, &queryPhoneObj{Phone: value, Md5: md5Str})
		app.Success(c, result)
	}
}
